import { useTitle } from 'ahooks'
import React, { useEffect, useRef, useState } from 'react'
import style from './Components/RefineOrder.less'
import pic from './Components/pic.svg'
import { Button, Checkbox, Dialog, Divider, Form, ImageUploadItem, ImageUploader, Input, Radio, Space } from 'antd-mobile'
import { CloseCircleOutline } from 'antd-mobile-icons'
import Item from 'antd-mobile/es/components/dropdown/item'
import { FormItem } from 'antd-mobile/es/components/form/form-item'
import p1 from '../Invoice/Components/p1.svg'
import p2 from '../Invoice/Components/p2.svg'
import p3 from '../Invoice/Components/p3.svg'
import example from '../Invoice/Components/example.svg'
import { history } from 'umi'
import { BillAdd } from '@/services/Title'
import { map } from 'lodash'


export default function RefineOrder() {
  useTitle('完善交易信息')
  const [check, setCheck] = useState<number>(1);
  const fileRef = useRef<any>([]);
  const [goodsList, setGoodsList] = useState<ImageUploadItem[]>([])
  const [fileList, setFileList] = useState<ImageUploadItem[]>([])
  const [fileList2, setFileList2] = useState<ImageUploadItem[]>([])
  const ListSortRef = useRef<any>()
  //接数据
  const goodsInfo = history.location.state
  console.log(goodsInfo);

  //判断货物数量
  if (goodsInfo?.state?.contacts.length <= 2) {
    //小于等于2 直接遍历 不做处理
    ListSortRef.current = [...goodsInfo?.state.contacts]
  } else {
    //排序处理，拿到总价最高的货物
    ListSortRef.current = [...goodsInfo?.state.contacts]
    ListSortRef.current = ListSortRef.current.sort(function (a, b) { return b.sum - a.sum }).slice(0, 2)
    // console.log(ListSortRef.current);
  }

  //交易校验框
  const onTrade = () => {
    Dialog.show({
      content: <span><span className={style.style_div1_span}>基础免验额度：</span><br />
        <span style={{ color: "rgba(166,166,166)" }}>每个自然人拥有连续12个月内<span style={{ color: "#21B47C" }}>6万元</span>的免验开票额度。超出后需完善交易信息再开票。（单笔部分超出的，整笔都需完善交易信息。）</span><br />

        <br /><span className={style.style_div1_span}>免验扣除规则：</span>
        <span style={{ color: "rgba(166,166,166)" }}> 去税局开票即冻结整笔订单金额，<span style={{ color: "#21B47C" }}>半小时</span>未开票、取消、废除开票即解除冻结，申请开票成功即扣除。</span><br />

        <br /><span className={style.style_div1_span}>先票后款额度：</span>
        <span style={{ color: "rgba(166,166,166)" }}> 每个自然人在完善交易时，拥有<span style={{ color: "#21B47C" }}>5张</span>先开具发票后补款（先票后款）订单机会。</span><br /><br />

        <span style={{ color: "rgba(166,166,166)" }}>去税局开票即视为已使用一张先票后款机会，取消或补款通过审核增加一张。<span style={{ color: "#21B47C" }}>使用上限为五张。</span></span></span>,
      closeOnAction: true,
      closeOnMaskClick: true,
      title: '交易真实性校验说明',
      actions: [[
        {

          key: "cancel",
          text: "取消",
          style: React.CSSProperties = { color: 'black' }
        },
        {

          key: "sure",
          text: "继续",
          style: React.CSSProperties = { color: 'rgba(33, 180, 124, 1)' }
        },]
      ],
    })
  }
  //判断是否使用先开票
  const onConfirm = (data: number) => {
    setCheck(data)
  }
  const onFinish = async(data: any) => {
    console.log('onfinish', data,check== 1?'先开发票':'上传凭证')
  var items:Array<API.goodsAddList> =[];
  var Name:any=[];
     (goodsInfo?.state?.contacts).forEach((i, index) => {
      Name.push(i?.cargoSorts)
      items.push({
        specification:i?.models,
        goodsName:i?.cargoSorts,
        amount:i?.cargoNumber,
        unitPrice:i?.unitPrice,
        totalMoney:i?.sum,
      })})


   const value:API.BillInfo={
     userId: 8,
     collectTicketsId: 6,
     businessPlace: "业务发生地",
     receiptAll: goodsInfo?.state?.total,
    //  carNumber: "车票号",
    //  remarks: "备注信息",
     image: "凭证图片",
     status:"待开票",
     invoicingMethod: "先票后款",
     enterprise: "收票企业",
     taxId: "M2923849222348",
     bankAddress: "银行地址",
     bankPhone: "银行电话",
     accountBank: "开户行",
     account: "开户账号",
     userPhone: "用户手机号",
     userName: "姓名",
     idNumber: "身份证号",
     goodsName: Name.toString(),
     goodsOrderAddDtos: items
   }
   console.log(value);
   
   const res = await BillAdd(value)
    console.log(res);
    

  }
  //凭证示例
  const onExamples = () => {
    Dialog.show({
      content: <span>
        <span style={{ fontSize: "14px", color: "#999999" }}>为保证审核顺利通过，请注意以下几点：</span><br />

        <div style={{ display: "flex", alignContent: "center" }}><img style={{ width: "18.5px", marginRight: "4.5px", height: "18.5px" }} src={p1} alt="" /><span style={{ fontSize: "14px", color: "#3D3D3D" }}>开票企业名称需与回单付款人名称一致；</span></div>

        <div style={{ display: "flex", alignContent: "center" }}><img style={{ width: "18.5px", height: "18.5px", marginRight: "4.5px" }} src={p2} alt="" /><span style={{ fontSize: "14px", color: "#3D3D3D" }}>回单金额不可小于交易金额；</span></div>

        <div style={{ display: "flex", alignContent: "center" }}><img style={{ width: "18.5px", height: "18.5px", marginRight: "4.5px" }} src={p3} alt="" /><span style={{ fontSize: "14px", color: "#3D3D3D" }}>收款人为个人 </span></div>
        <br />
        <span style={{ fontSize: "14px", color: "#BC944E" }}>回单示例</span>
        <img style={{ width: "100%" }} src={example} alt="" />
      </span>,
      closeOnAction: true,
      closeOnMaskClick: true,
      title: '付款凭证说明及示例',

      actions: [
        {

          key: "sure",
          text: "关闭",
          style: React.CSSProperties = { color: '#21B47C' }
        },
      ]
    })
  }
  //照片文件监听
  async function mockUpload(file: File) {
    fileRef.current = file
    console.log(file);

    // await sleep(3000)
    return {
      url: URL.createObjectURL(file),
    }
  }

  useEffect(() => {

  }, [])
  return (
    <Form
      onFinish={onFinish}
      footer={
        <div className={style.style_footer}>
          <div>
            <div style={{ color: "red" }}>¥<span style={{ fontSize: "18px", fontWeight: "bold" }}>{goodsInfo?.state?.total?.toLocaleString()} </span></div>
            <div style={{ color: "#999999", fontSize: "10px", height: "14px", lineHeight: "14px", margin: "1px" }}>订单总金额</div>
          </div>
          <div >
            <Button onClick={() => {
              {goodsInfo?.state?.path=='/Invoice/RecordSure'?
              history.push(
                '/Invoice/RecordSure',
                { state: goodsInfo?.state }
              )
              :
              history.go(-1)
            }
              
              
            }} style={{ border: "1px solid #21B47C", "--text-color": "#21B47C" }}>上一步</Button>
            <Button type='submit' style={{ background: "#21B47C", "--text-color": "#FFFFFF", marginLeft: "10px" }}>开票</Button>
          </div>
        </div>
      }>
      <div className={style.styles}>

        <div className={style.style_div1}>
          <div className={style.style_div1_span}>上传交易商品照片</div>
          <div className={style.style_div1_1}>
            <Form.Item name='pic1'>
              <ImageUploader
                style={{ '--cell-size': '50px' }}
                maxCount={1}
                value={ fileList}
                onChange={setFileList}
                upload={mockUpload}
              ><img style={{ width: "50px" }} src={pic} alt="" /></ImageUploader>
            </Form.Item>
            <span style={{ marginLeft: "14px", fontSize: "15px", color: "#333333" }}>{ListSortRef.current[0]?.cargoSorts}</span>
          </div>
          {goodsInfo?.state?.contacts.length>=2?
          <div className={style.style_div1_1}>
            <Form.Item name='pic2'>
              <ImageUploader
                style={{ '--cell-size': '50px' }}
                maxCount={1}
                value={ fileList2}
                onChange={setFileList2}
                upload={mockUpload}
              ><img style={{ width: "50px" }} src={pic} alt="" /></ImageUploader>
            </Form.Item>
            <span style={{ marginLeft: "14px", fontSize: "15px", color: "#333333" }}>{ListSortRef.current[1]?.cargoSorts}</span>
          </div>:''}



        </div>
        {goodsInfo?.state?.total <= 10000 ? '' :
          <div className={style.style_div2}>
            <div className={style.style_div1_span}>开票方式</div>
            <div className={style.style_div2_buttons}>
              <Button onClick={() => onConfirm(1)} style={{ marginRight: "10px", width: "162.5px", height: "35px", lineHeight: "17.5px", "--background-color": check != 1 ? "#F4F4F4" : 'rgba(33, 180, 124, 1)', "--text-color": check == 1 ? "#FFFFFF" : "" }}><span style={{ "fontSize": "14px" }}>先开发票<span style={{ fontSize: "12px" }}>(剩余5张)</span></span></Button>
              <Button onClick={() => onConfirm(2)} style={{ width: "162.5px", height: "35px", lineHeight: "17.5px", "--background-color": check == 1 ? "#F4F4F4" : 'rgba(33, 180, 124, 1)', "--text-color": check != 1 ? "#FFFFFF" : "" }} ><span style={{ "fontSize": "14px" }}>付款校验</span></Button>
            </div>
            <div style={{ display: check != 1 ? 'block' : 'none' }}>
              <div className={style.div2_3}>
                <div style={{ fontSize: "15px", color: "#666666" }}>支付方式</div>
                <Radio.Group >
                  <Space style={{ "--gap-horizontal": "20px" }}>
                    <Radio defaultChecked style={{
                      '--icon-size': '16px',
                      '--font-size': '15px',
                      '--gap': '5px',
                    }}>上传付款凭证</Radio>
                    <Radio disabled
                      icon={() => <CloseCircleOutline style={{ opacity: 0.3 }} />}
                      style={{
                        '--icon-size': '16px',
                        '--font-size': '15px',
                        '--gap': '5px',
                      }}>
                      在线支付</Radio></Space>
                </Radio.Group>
              </div>
              <hr className={style.style_div2_hr} />
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: "10px" }}>
                <div style={{ fontSize: "15px", color: "#666666" }}>上传付款凭证</div>
                <div onClick={onExamples} style={{ fontSize: "13px", color: "#BC944E" }}>付款凭证声明及示例</div>
              </div>

              <div >
                <Form.Item
                  name='voucher'
                >
                  <ImageUploader
                    style={{ '--cell-size': '50px' }}
                    maxCount={1}
                    value={goodsList}
                    onChange={setGoodsList}
                    upload={mockUpload}

                  ><img style={{ width: "50px" }} src={pic} alt="" /></ImageUploader>
                </Form.Item>
              </div>
            </div>
          </div>}

        <span onClick={() => onTrade()} style={{ color: "rgba(33, 180, 124, 1)", fontSize: "13px", marginLeft: "10px", marginTop: "10px" }}>交易校验规则</span>

      </div>
    </Form>
  )
}
